package cn.com.open.itembank.util;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * The type File utils.
 */
public class FileUtils {

    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(FileUtils.class);

    //region 删除给定文件夹下的最后编辑时间和当前时间差大于1天的历史文件

    /**
     * 删除给定文件夹下的最后编辑时间和当前时间差大于1天的历史文件.
     *
     * @param direcotry 给定文件夹
     */
    public static void deleteOldFiles(File direcotry) {
        //如果文件是文件夹并且存在
        if (direcotry.exists() && direcotry.isDirectory()) {
            //获取所有文件列表
            File[] fileList = direcotry.listFiles();
            //获取当前时间
            long now = System.currentTimeMillis();
            //遍历文件
            for (File file : fileList) {
                //如果是文件类型
                if (file.isFile()) {
                    //获取最后编辑时间
                    long lastModified = file.lastModified();
                    //如果最后编辑时间和当前时间差大于一天，则删除文件
                    if (now - lastModified > (1000 * 3600 * 24)) {
                        file.delete();
                    }
                }
            }
        }
    }
    //endregion

    //region 创建目录

    /**
     * 创建目录.
     *
     * @param destDirName 文件夹路径
     * @return the boolean
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败，目标目录已存在！");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            System.out.println("创建目录成功！" + destDirName);
            return true;
        } else {
            System.out.println("创建目录失败！");
            return false;
        }
    }
    //endregion

    //region 将图片文件读取到内存

    /**
     * 将图片文件读取到内存.
     *
     * @param path the path
     * @return the byte [ ]
     * @throws IOException the io exception
     */
    public static byte[] image2byte(String path) throws IOException {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
        } catch (FileNotFoundException ex) {
            logger.error(ex.getMessage());
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        } finally {
            if (input != null) {
                input.close();
            }
        }
        return data;
    }
    //endregion

    //region 读取输入文件流

    /**
     * 读取输入文件流.
     *
     * @param inStream the in stream
     * @return the byte [ ]
     * @throws IOException the io exception
     */
    public static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }
    //endregion

    //region 将网络文件写到本地

    /**
     * 将网络文件写到本地.
     *
     * @param urlFile    the url file
     * @param nativeFile the native file
     * @throws IOException the io exception
     */
    public static void writeUrlFileToLocal(String urlFile, String nativeFile) throws IOException {
        FileOutputStream outStream = null;
        try {
            //new一个URL对象
            URL url = new URL(urlFile);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = readInputStream(inStream);
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File(nativeFile);
            //创建输出流
            outStream = new FileOutputStream(imageFile);
            //写入数据
            outStream.write(data);
            //关闭输出流
            outStream.close();
        } catch (IOException ex1) {
            logger.error(ex1.getMessage());
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }
    }
    //endregion

    //region 将文件字节数组写到本地

    /**
     * 将文件字节数组写到本地.
     *
     * @param data       the data
     * @param nativeFile the native file
     * @throws IOException the io exception
     */
    public static File writeFileDataToLocal(byte[] data, String nativeFile) throws IOException {
        FileOutputStream outStream = null;
        try {
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File saveFile = new File(nativeFile);
            //创建输出流
            outStream = new FileOutputStream(saveFile);
            //写入数据
            outStream.write(data);
            System.out.println(saveFile.getAbsolutePath());
            //关闭输出流
            outStream.close();

            return saveFile;
        } catch (IOException ex1) {
            logger.error(ex1.getMessage());
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }

        return null;
    }
    //endregion

}
